package com.example.migrator.controller;

import com.example.migrator.service.MigrationService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/migration")
public class MigrationController {

    private static final Logger logger = LoggerFactory.getLogger(MigrationController.class);

    @Autowired
    private MigrationService<Object> migrationService;

    /**
     * 迁移指定表的数据
     */
    @PostMapping("/migrate/{tableName}")
    public ResponseEntity<Map<String, Object>> migrateData(
            @PathVariable String tableName,
            @RequestParam(defaultValue = "1000") int batchSize) {
        Map<String, Object> response = new HashMap<>();
        try {
            logger.info("开始迁移表 {} 的数据，批次大小: {}", tableName, batchSize);
            long totalCount = migrationService.migrateData(tableName, batchSize);
            response.put("success", true);
            response.put("message", "数据迁移成功");
            response.put("totalCount", totalCount);
            return new ResponseEntity<>(response, HttpStatus.OK);
        } catch (Exception e) {
            logger.error("迁移表 {} 的数据时发生错误: {}", tableName, e.getMessage(), e);
            response.put("success", false);
            response.put("message", e.getMessage());
            return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    /**
     * 带条件迁移指定表的数据
     */
    @PostMapping("/migrate/{tableName}/with-condition")
    public ResponseEntity<Map<String, Object>> migrateDataWithCondition(
            @PathVariable String tableName,
            @RequestParam String whereClause,
            @RequestParam(defaultValue = "1000") int batchSize) {
        Map<String, Object> response = new HashMap<>();
        try {
            logger.info("开始带条件迁移表 {} 的数据，条件: {}, 批次大小: {}", 
                    tableName, whereClause, batchSize);
            long totalCount = migrationService.migrateDataWithCondition(tableName, whereClause, batchSize);
            response.put("success", true);
            response.put("message", "条件数据迁移成功");
            response.put("totalCount", totalCount);
            return new ResponseEntity<>(response, HttpStatus.OK);
        } catch (Exception e) {
            logger.error("带条件迁移表 {} 的数据时发生错误: {}", tableName, e.getMessage(), e);
            response.put("success", false);
            response.put("message", e.getMessage());
            return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    /**
     * 验证数据一致性
     */
    @GetMapping("/verify/{tableName}")
    public ResponseEntity<Map<String, Object>> verifyData(@PathVariable String tableName) {
        Map<String, Object> response = new HashMap<>();
        try {
            logger.info("开始验证表 {} 的数据一致性", tableName);
            boolean isConsistent = migrationService.verifyData(tableName);
            response.put("success", true);
            response.put("consistent", isConsistent);
            response.put("message", isConsistent ? "数据一致" : "数据不一致");
            return new ResponseEntity<>(response, HttpStatus.OK);
        } catch (Exception e) {
            logger.error("验证表 {} 的数据一致性时发生错误: {}", tableName, e.getMessage(), e);
            response.put("success", false);
            response.put("message", e.getMessage());
            return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    /**
     * 获取表的元数据信息
     */
    @GetMapping("/metadata/{tableName}")
    public ResponseEntity<Map<String, Object>> getTableMetadata(@PathVariable String tableName) {
        Map<String, Object> response = new HashMap<>();
        try {
            logger.info("开始获取表 {} 的元数据信息", tableName);
            List<String> metadata = migrationService.getTableMetadata(tableName);
            response.put("success", true);
            response.put("metadata", metadata);
            return new ResponseEntity<>(response, HttpStatus.OK);
        } catch (Exception e) {
            logger.error("获取表 {} 的元数据信息时发生错误: {}", tableName, e.getMessage(), e);
            response.put("success", false);
            response.put("message", e.getMessage());
            return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    /**
     * 获取表的记录总数
     */
    @GetMapping("/count/{tableName}")
    public ResponseEntity<Map<String, Object>> getTableCount(@PathVariable String tableName) {
        Map<String, Object> response = new HashMap<>();
        try {
            logger.info("开始获取表 {} 的记录总数", tableName);
            long count = migrationService.getTableCount(tableName);
            response.put("success", true);
            response.put("count", count);
            return new ResponseEntity<>(response, HttpStatus.OK);
        } catch (Exception e) {
            logger.error("获取表 {} 的记录总数时发生错误: {}", tableName, e.getMessage(), e);
            response.put("success", false);
            response.put("message", e.getMessage());
            return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    /**
     * 健康检查接口
     */
    @GetMapping("/health")
    public ResponseEntity<Map<String, Object>> healthCheck() {
        Map<String, Object> response = new HashMap<>();
        response.put("status", "UP");
        response.put("message", "Oracle to MySQL MyBatis Migrator is running");
        return new ResponseEntity<>(response, HttpStatus.OK);
    }
}